//
//  ManagerViewController.m
//  HomeDelivery
//
//  Created by apple on 16/7/25.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ManagerViewController.h"
#import "OrderCenterCell.h"
#import "OrderListData.h"
#import "OrderDatailViewController.h"
@interface ManagerViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger _selectedIndex;
    UIView *_lingeView;
    NSInteger _pageIndex;
}
@property(nonatomic,strong)UITableView *mainTableView;
@property(nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation ManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"订单中心";
    self.view.backgroundColor=GRAYCOLOR;
    _dataSource=[NSMutableArray array];
    [self setUpSegmentCtl];
    [self.view addSubview:self.mainTableView];
}
#pragma mark--请求数据
-(void)getData
{
   // http://192.168.1.107:35568/Order/OrderList/{MerchantAccId}/{OrderStatus}/{SpanTimeID}/{ReserveDate}/{SearchKey}/{PageIndex}/{PageSize}/{Timestamp}/{Sign}
    //OrderStatus：30 待取件，60 洗涤中，90 待送件；SpanTimeID和ReserveDate传-1；SearchKey：传NOKEY；
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSString *pageIndex=[NSString stringWithFormat:@"%zd",_pageIndex];
    NSString *orderStatus=[NSString stringWithFormat:@"%zd",_selectedIndex];
    if (MERCHANTACCID) {
        NSDictionary *dic=@{@"MerchantAccId":MERCHANTACCID,
                            @"AdminAccount":ADMINACCOUNT,
                            @"OrderStatus":orderStatus,
                            @"SpanTimeID":@"-1",
                            @"ReserveDate":@"-1",
                            @"SearchKey":@"NOKEY",
                            @"PageIndex":pageIndex,
                            @"PageSize":@"10",
                            @"Timestamp":timeStamp};
        NSString *sign=[GeneralTool GetSin:dic];
        NSString *urlString=[NSString stringWithFormat:@"Order/OrderList/%@/%@/%@/%@/%@/%@/%@/%@/%@/%@",MERCHANTACCID,ADMINACCOUNT,orderStatus,@"-1",@"-1",@"NOKEY",pageIndex,@"10",timeStamp,sign];
        [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andFinishedWith:^(id response, NSError *error)
         {
             [MBProgressHUD hideHUDForView:self.view];
             if (error)
             {
                 [_mainTableView.mj_header endRefreshing];
                 [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                 [MBProgressHUD showError:@"请求失败"];
             }else
             {
                 if ([response[@"IsSuccess"]integerValue]==1)
                 {
                     NSDictionary *dic=response[@"ReturnObject"];
                     
                     if (dic[@"OrderList"]==[NSNull null])
                     {
                         [_mainTableView.mj_header endRefreshing];
                         [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                     }else
                     {
                         NSArray *arrList=dic[@"OrderList"];
                         for (NSDictionary *dataDic in arrList)
                         {
                             OrderListData *data=[[OrderListData alloc]init];
                             [data setValuesForKeysWithDictionary:dataDic];
                             [self.dataSource addObject:data];
                         }
                         if (arrList.count<10) {
                             [_mainTableView.mj_header endRefreshing];
                             [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                         }else
                         {
                             
                              [_mainTableView.mj_footer endRefreshing];
                         }
                         [_mainTableView.mj_header endRefreshing];
                         [_mainTableView reloadData];
                     }
                    
                     
                 }else
                 {
                     [MBProgressHUD showError:response[@"ReturnString"]];
                       [_mainTableView.mj_header endRefreshing];
                 }
             }
           
            
         }];
        
 
    }
}
#pragma mrak--表
-(UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64+48.5, WIDTH, HEIGHT-64-48.5-49) style:UITableViewStylePlain];
        _mainTableView.backgroundColor=LIGHTGRAY;
        _mainTableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheTableView)];
        _mainTableView.mj_footer=[MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addMoreData)];
        [_mainTableView registerNib:[UINib nibWithNibName:@"OrderCenterCell" bundle:nil] forCellReuseIdentifier:@"reuse"];
        _mainTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _mainTableView.dataSource=self;
        _mainTableView.delegate=self;
        _mainTableView.tableFooterView=[UIView new];
        
    }
    return _mainTableView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderListData *data=self.dataSource[indexPath.section];
    CGFloat height=[data.UAddress boundingRectWithSize:CGSizeMake(WIDTH-20-110, 200) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size.height;
    return 175+height;
}
//刷新
-(void)refreshTheTableView
{
    _pageIndex=1;
    [_dataSource removeAllObjects];
    [_mainTableView reloadData];
    [self getData];
}
//加载
-(void)addMoreData
{
    _pageIndex++;
    [self getData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderCenterCell *cell=[tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    OrderListData *data=self.dataSource[indexPath.section];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.orderLbl.text=data.OrderID;
    cell.timeLbl.text=data.OrderDate;
    cell.addressLbl.text=data.UAddress;
    cell.dateNameLbl.text=data.DateName;
    NSMutableAttributedString *str=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@  ",data.ReceiveName] attributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor]}];
    NSAttributedString *string=[[NSAttributedString alloc]initWithString:data.Mobile attributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle],NSForegroundColorAttributeName:BLUECOLOR}];
    [str appendAttributedString:string];
    [cell.peopleBtn setAttributedTitle:str forState:UIControlStateNormal];
    cell.peopleBtn.tag=indexPath.section;
    [cell.peopleBtn addTarget:self action:@selector(call:) forControlEvents:UIControlEventTouchUpInside];
     CGFloat height=[data.UAddress boundingRectWithSize:CGSizeMake(WIDTH-20-110, 50) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size.height;
    [cell refreshLabelWithFrame:cell.addressLbl.frame andHeight:height/2.0];
    return cell;
}
-(void)call:(UIButton *)btn
{
    OrderListData *data=self.dataSource[btn.tag];
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",data.Mobile];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderListData *data=self.dataSource[indexPath.section];
    OrderDatailViewController *orderDetail=[[OrderDatailViewController alloc]init];
    orderDetail.hidesBottomBarWhenPushed=YES;
    orderDetail.orderID=data.OrderID;
    [self.navigationController pushViewController:orderDetail animated:YES];
}
#pragma mark--选择条
-(void)setUpSegmentCtl
{
    CGFloat width=WIDTH/3.0;
    for (int i=0; i<3; i++)
    {
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(i*width, 64, width, 48)];
        [btn setTitle:@[@"待取件",@"洗涤中",@"待送件"][i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        btn.backgroundColor=LIGHTGRAY;
        btn.titleLabel.font=[UIFont systemFontOfSize:15];
        btn.tag=(i+1)*30;
        if (i==0)
        {
            [btn setTitleColor:ORANGE forState:UIControlStateNormal];
                _selectedIndex=btn.tag;
        }
        [btn addTarget:self action:@selector(clickOnSegmentCtl:) forControlEvents:UIControlEventTouchUpInside];
               [self.view addSubview:btn];
    }
    
    _lingeView=[[UIView alloc]initWithFrame:CGRectMake(0, 64+47, width, 1.5)];
    _lingeView.backgroundColor=ORANGE;
    [self.view addSubview:_lingeView];
}
-(void)clickOnSegmentCtl:(UIButton *)btn
{
    UIButton *button=[self.view viewWithTag:_selectedIndex];
    [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [btn setTitleColor:ORANGE forState:UIControlStateNormal];
    _selectedIndex=btn.tag;
    
    [UIView animateWithDuration:0.1 animations:^{
        CGRect rect=_lingeView.frame;
        rect.origin.x=btn.frame.origin.x;
        _lingeView.frame=rect;
    }];
    [self.mainTableView.mj_header beginRefreshing];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor=ORANGE;
      self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:18]};
    [self.mainTableView.mj_header beginRefreshing];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
